//
//  StatusCell.swift
//  weibo
//
//  Created by sanya on 15/6/30.
//  Copyright © 2015年 sanya. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage

protocol StatusCellDelegate:NSObjectProtocol {
    /// 照片选择的代理方法
    func statusCellDidSelectedPhoto(cell:StatusCell, photoIndex:Int)
}
/// 图片视图可重用标示符
let SYNormalPictureCellReuseIdentifier = "SYNormalPictureCellReuseIdentifier"
let SYForwardPictureCellReuseIdentifier = "SYForwardPictureCellReuseIdentifier"

private let SYPictureCellReuseIdentifier = "SYPictureCellReuseIdentifier"
class StatusCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate{
    
    /// 配图视图宽度约束
    var widthCons: NSLayoutConstraint?
    /// 配图视图高度约束
    var heigthCons:NSLayoutConstraint?
    
    var topCons:NSLayoutConstraint?
    weak var photoDelegate:StatusCellDelegate?
    
    /// 转发微博标签
    var forwardLabel: UILabel?
    
    
    var status: Status? {
        didSet{
            // 设置数据
            nameLabel.text = status?.user?.name
            timeLabel.text = status?.created_at
            sourceLabel.text = "刚刚"
            iconView.sd_setImageWithURL(status?.user?.profileURL)
            vipIconView.image = status?.user?.verifiedImage
            memberIconView.image = status?.user?.mbImage
            contentLalel.text = status?.text
            
            // 转发文字
            forwardLabel?.text = (status?.retweeted_status?.user?.name ?? "") + " : " + (status?.retweeted_status?.text ?? "")
            
            // 计算视图的大小
            let size = calcPictureViewSize(status!)
            topCons?.constant = size.itemSize.height == 0 ? 0 : 12
            widthCons?.constant = size.viewSize.width
            heigthCons?.constant = size.viewSize.height
            pictureLayout.itemSize = size.itemSize
            // 刷新图片视图
            pictureView.reloadData()
        }
    }
    
    /// 计算行高
    func rowheight(status:Status) -> CGFloat{
        // 给模型设置数值，调用didSet方法
        self.status = status
        // 更新布局
        layoutIfNeeded()
        // 返回行高- 页脚视图的底边
        return CGRectGetMaxY(foorView.frame)
    }
    
    /// 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.picURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        
        let cell =  collectionView.dequeueReusableCellWithReuseIdentifier(SYPictureCellReuseIdentifier, forIndexPath: indexPath) as! StatusPictureCell
        
        cell.imageURL = status?.picURLs![indexPath.item]
        
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("okk")
        photoDelegate?.statusCellDidSelectedPhoto(self, photoIndex: indexPath.item)
        
    }
    ///  根据微博模型计算图片是的大小
    /**
    0. 没有图片，返回zero
    1. 单图会按照图片等比例显示
    2. 多图的图片大小固定
    3. 多图如果是4张，会按照 2 * 2 显示
    4. 多图其他数量，按照 3 * 3 九宫格显示
    */
    private func calcPictureViewSize(status:Status) -> (viewSize:CGSize,itemSize:CGSize){
        // 0. 获取图片数量
        let count = status.picURLs?.count ?? 0
        
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        // 1. 没有图片
        if count == 0 {
            return (CGSizeZero,itemSize)
        }
        // 2. 单图
        if count == 1 {
            // 1> 从缓存拿到并且创建 image
            // key 就是URL的完整字符串， sdwebimage 缓存图片文件名是对url完整字符串进行md5
            let key = status.picURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
//            print("单图\(key)\(image.size)")
            return (image.size,image.size)
            
        }
        // 3. 4张图片
        if count == 4 {
            let w = itemSize.width * 2 + margin
            return (CGSize(width: w, height: w),itemSize)
        }
        // 4. 多张图片
        // 每行图片数量
        let rowCount = 3
        // 行号
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + margin * CGFloat(rowCount - 1)
        let h = itemSize.height * CGFloat(row) + margin * CGFloat(row - 1)
    
        return (CGSize(width: w, height: h),itemSize)
    }
    /// 初始化方法
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        // 屏幕宽度
        let screenWidth = UIScreen.mainScreen().bounds.width
        
        // 顶部视图
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.5, alpha: 1.0)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: screenWidth, height: 10))
        
        addSubview(iconView)
        addSubview(nameLabel)
        addSubview(memberIconView)
        addSubview(vipIconView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(contentLalel)
        contentLalel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 16
        addSubview(pictureView)
        addSubview(foorView)
        foorView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        // 准备配图视图
        preparePictureView()
        
        // 头像
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 34, height: 34), offset: CGPoint(x: 12, y: 22))
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8))
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        contentLalel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))

        // 页脚视图
        foorView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenWidth, height: 44), offset: CGPoint(x: -12, y: 12))
    }
    
    // 如果使用 sb & xib 开发，使用 fatalError 会直接崩掉
    required init(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
    }
    /// 记录配图视图约束
    func recordPictureCons(Cons:[NSLayoutConstraint]){
        // 记录宽高约束
        widthCons = pictureView.ff_Constraint(Cons, attribute: NSLayoutAttribute.Width)
        heigthCons = pictureView.ff_Constraint(Cons, attribute: NSLayoutAttribute.Height)
        topCons = pictureView.ff_Constraint(Cons, attribute: NSLayoutAttribute.Top)
    
    }
    /// 获取重用cell 的ID
    class func cellIdentifier(status: Status) -> String {
        return status.retweeted_status != nil ? SYForwardPictureCellReuseIdentifier : SYNormalPictureCellReuseIdentifier
    }
    
    /// 准备配图视图
    private func preparePictureView(){
        // 1.设置背景颜色
        pictureView.backgroundColor = UIColor.whiteColor()
        // 2.数据源
        pictureView.dataSource = self
        pictureView.delegate = self
        // 3.注册可重用cell
        pictureView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: SYPictureCellReuseIdentifier)
        // 4. 设置layout
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
    }
    // MARK - 懒加载
    // 头像
    lazy var iconView = UIImageView()
    // 名称
    lazy var nameLabel:UILabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
    
    lazy var memberIconView:UIImageView = UIImageView()
    lazy var vipIconView:UIImageView = UIImageView()
    
    lazy var timeLabel:UILabel = UILabel(color: UIColor.orangeColor(), fontSize: 10)
    
    lazy var sourceLabel:UILabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
    lazy var contentLalel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15, mutiLines: true)
    
    // 图像视图
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)
    // 底部视图
    lazy var foorView:StatusFooterView = StatusFooterView()
    
}

// 自定义cell 类，微博图片
private class StatusPictureCell:UICollectionViewCell {
    var imageURL:NSURL?{
        didSet{
            iconView.progress = 0
            // 如果本地有`缓存`，直接加载本地缓存的图片，如果没有，会自动下载
            // SDWebImage 虽然支持 gif 格式，但是内存消耗比较大！
            iconView.sd_setImageWithURL(imageURL)
            // 根据 URL 的扩展名 判断是否是gif / GIF
            gifIconView.hidden = !(imageURL?.absoluteString.pathExtension.lowercaseString == "gif")
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true
    
        addSubview(iconView)
        iconView.ff_Fill(self)
        iconView.addSubview(gifIconView)
        gifIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil)
    }
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 微博图片
    private lazy var iconView:SYImageView = SYImageView()
    
    private lazy var gifIconView:UIImageView = {
        let iv = UIImageView(image: UIImage(named: "timeline_image_gif"))
        iv.hidden = true
        return iv
    }()
}
// 底部视图类
class StatusFooterView:UIView{
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        addSubview(forwarBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        // 平铺
        ff_HorizontalTile([forwarBtn,commentBtn,likeBtn], insets: UIEdgeInsetsZero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 懒加载
    lazy var forwarBtn:UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", fontSize: 12)
 
    lazy var commentBtn:UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", fontSize: 12)
    lazy var likeBtn:UIButton = UIButton(title: "点赞", imageName: "timeline_icon_unlike", fontSize: 12)

}

